package com.rs.service.impl;

import cn.hutool.core.date.DateUtil;
import com.rs.config.CurrentUser;
import com.rs.dao.StudentDAO;
import com.rs.dao.TermDAO;
import com.rs.entity.Student;
import com.rs.entity.Term;
import com.rs.entity.TermExample;
import com.rs.entity.excel.StudentExcelEntity;
import com.rs.service.TermService;
import com.rs.util.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 学期service实现
 */
@Service
public class TermServiceImpl implements TermService {
    @Autowired
    private TermDAO termDAO;
    @Autowired
    private StudentDAO studentDAO;

    @Override
    public Term getByKey(Integer id) {
        return termDAO.selectByPrimaryKey(id);
    }

    @Override
    public List<Term> list(String name) {
        return termDAO.selectList(name);
    }

    @Override
    public  List<Map> maplist(){

        return termDAO.maplist();
    }

    @Override
    public int save(Integer id, String name,String no) {
        if (id >0) {
            Term term = new Term();
            term.setId(id);
            term.setNo(no);
            term.setName(name);
            term.setUpdateTime(DateUtil.now());
            term.setUpdateUser(CurrentUser.getUserId());
            return termDAO.updateByPrimaryKeySelective(term);
        }
        Term term = new Term();
        term.setName(name);
        term.setNo(no);
        term.setCreateTime(DateUtil.now());
        term.setCreateUser(CurrentUser.getUserId());
        term.setUpdateTime(DateUtil.now());
        term.setUpdateUser(CurrentUser.getUserId());
        return termDAO.insertSelective(term);
    }

    @Override
    public Boolean delete(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        for (Integer id : ids) {
            termDAO.deleteByPrimaryKey(id);
        }
        return true;
    }

    @Override
    public void saveStudents(Integer termId, List<StudentExcelEntity> list) {

        // TODO 改为批量insert，效率 指数递增。
        for (StudentExcelEntity entity : list) {
            Student student = new Student();
            student.setStudentNo(entity.getStudentNo());
            student.seteMail(entity.getEmail());
            student.setGender(entity.getGender());
            student.setName(entity.getName());
            student.setMoblephone(entity.getMobilePhone());
            student.setPassword(Md5Utils.getMD5("123456", "utf-8"));

            studentDAO.insert(student);
        }


    }

    @Override
    public Map getListByStudent(){


        return termDAO.getListByStudent();
    }

}
